<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014-2018 东莞市云拓互联网络科技有限公司
// +----------------------------------------------------------------------
// | 官方网站:http://www.ytclouds.net
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

namespace app\webapi\service;

use think\Db;
use app\webapi\service\AppuserService;

/**
 * 产品数据服务支持
 * Class ProductService
 * @package app\goods\service
 */
class LotteryService
{

    /**
     * 获取抽奖规则
     */
    public static function get_rule(&$lottery_list, $type = 0)
    {
        $where = [];
        if ($type == 0) {
            $where['id'] = 1;
        } else if ($type == 1) {
            $where['id'] = 2;
        }
        $lottery_config = Db::name("LotteryConfig")->where($where)->find();
        $lottery_list['rule'] = $lottery_config['rule'] ? $lottery_config['rule'] : '';
        $lottery_list['lottery_help'] = $lottery_config['lottery_help'] ? $lottery_config['lottery_help'] : '';
        return $lottery_list;
    }

    /**
     * 获取中奖者
     * @param $lottery_list
     * @return array
     */
    public static function get_winners(&$lottery_list, $type = 0)
    {
        $join = [
            ['app_users w', 'a.user_id=w.id'],
            ['lottery_pool c', 'a.lottery_pool_id=c.id'],
        ];
        $fields = "a.*,w.nickname,c.copywriter2,c.original_img,c.goods_name";
        $where = "a.type = " . $type . ' and a.good_name != "谢谢惠顾" ';

        $winners = Db::table('lottery_winner')
            ->alias('a')
            ->join($join)
            ->where($where)
            ->field($fields)
            ->limit(0, 30)
            ->select();
        foreach ($winners as $key => $val) {
            $winners[$key]['addtime'] = date("Y-m-d H:i:s", $val['addtime']);
        }
        $lottery_list['winners'] = $winners;
        return $lottery_list;
    }

    /**
     * 获取我的中奖记录
     */
    public static function get_my_pool($user_id)
    {
        $join = [
            ['app_users w', 'a.user_id=w.id'],
            ['lottery_pool c', 'a.lottery_pool_id=c.id'],
        ];
        $fields = "a.*,w.nickname,c.copywriter2,c.original_img,c.goods_name,c.href";

        $res = Db::table('lottery_winner')
            ->alias('a')
            ->join($join)
            ->where("a.user_id =" . $user_id . " and a.good_name !='谢谢惠顾'")
            ->field($fields)
            ->select();
        return $res;
    }


    /**
     * 抽奖操作
     * @param $user_id
     * @param $lottery_list
     * @return array
     */
    public static function play($user_id, $lottery_list = null, $type = 0)
    {
        //判断是否有抽奖次数
        $user_data = AppuserService::get_user_data($user_id, 'lottery_count,lottery_high_count');
        if ($type == 0) {
            if ($user_data['lottery_count'] <= 0) {
                return ['status' => -1, 'msg' => '你抽奖次数已经用完', 'result' => []];
            }
        } else {
            if ($user_data['lottery_high_count'] <= 0) {
                return ['status' => -1, 'msg' => '你抽奖次数已经用完', 'result' => []];
            }
        }
        //设置奖池
        $pool = $lottery_list ? $lottery_list : self::get_pool($type);
        //抽奖
        $result = self::do_play($pool);
        if (!$result) {
            if ($type == 0) {
                $new_count = $user_data['lottery_count'];
            } else {
                $new_count = $user_data['lottery_high_count'];
            }
            return array('status' => -1, 'msg' => '奖品区没奖品', 'result' => '', 'cardNum' => 1, 'new_count' => $new_count);
        }

        //减少抽奖次数
        AppuserService::user_lottery_count_dec($user_id, $type);
        $new_user_data = AppuserService::get_user_data($user_id, 'lottery_count,lottery_high_count');
        if ($type == 0) {
            $new_count = $new_user_data['lottery_count'];
        } else {
            $new_count = $new_user_data['lottery_high_count'];
        }

        if ($result[1] == 0)
            return array('status' => 200, 'msg' => $result[0], 'result' => '', 'cardNum' => $result[2], 'new_count' => $new_count);
        //中奖处理，减少奖品的数量，生成CDK码，方便以后兑换
        Db::startTrans();
        $set_dec_goods = self::set_dec_goods($result[1]);
        if ($set_dec_goods) {
            $add_winner = self::lottery_winner_log($user_id, $result[1], $result[0], $set_dec_goods, $type);
            if (!$add_winner) {
                // 回滚事务
                Db::rollback();
                return array('status' => 2, 'msg' => '遗憾了，没中奖', 'result' => '', 'cardNum' => 1, 'new_count' => $new_count);
            }
            Db::commit();
            //生成CDK,录入中奖表
            $addData = [
                'winningUser' => $add_winner
            ];
            return array('status' => 200, 'msg' => '恭喜你抽中了' . $result[0], 'result' => $addData, 'cardNum' => $result[2], 'new_count' => $new_count);
        }
        if($result[2] == 1){
            $add_winner = self::lottery_winner_log($user_id, $result[1], $result[0], '', $type);
            return array('status' => 200, 'msg' => '遗憾了，没中奖', 'result' => $add_winner, 'cardNum' => 1, 'new_count' => $new_count);
        }else{
            return array('status' => 200, 'msg' => '遗憾了，没中奖', 'result' => '', 'cardNum' => 1, 'new_count' => $new_count);
        }
    }


    /**
     * 奖品录入
     * @param $user_id
     * @param $prize_id
     */
    public static function lottery_winner_log($user_id, $prize_id, $good_name, $cdkey, $type = 0)
    {
        $addtime = time();
        $data = ['user_id' => $user_id, 'good_name' => $good_name, 'lottery_pool_id' => $prize_id, 'cdkey' => $cdkey, 'addtime' => $addtime, 'type' => $type];
        $res = Db::table('lottery_winner')->insert($data);
        if (!$res) {
            return false;
        }
        $arr = [];
        $prize_info = Db::name("LotteryPool")->where(['id' => $prize_id])->find();
        $arr['prize_id'] = $prize_info['id'];
        $arr['original_img'] = $prize_info['original_img'];
        $arr['copywriter1'] = $prize_info['goods_name'];
        $arr['copywriter2'] = $prize_info['copywriter2'];
        return $arr;
    }


    /**
     * 中奖，减少奖品数量
     * @param $prize_id
     */
    public static function set_dec_goods($prize_id)
    {
        $prize_info = Db::name('LotteryPool')->where(['id' => $prize_id])->find();
        if ($prize_info['is_free'] == 1) {
//            谢谢惠顾
            return false;
        }
        if ($prize_info['goods_num'] <= 0) {
            return false;
        }
        Db::startTrans();

        $res = Db::name('LotteryPool')->where(['id' => $prize_id])->setDec('goods_num');
        if (!$res) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        //获取cdkey
        $cdkey = self::get_cdkey($prize_id);
        if ($cdkey) {
            // 提交事务
            Db::commit();
            return $cdkey;
        }
        // 回滚事务
        Db::rollback();
        return false;
    }

    /**
     * 获取cdkey
     * @param $prize_id
     */
    public static function get_cdkey($prize_id)
    {
        $get_one_cdkey = Db::name("LotteryCdkey")
            ->where(['lottery_pool_id' => $prize_id, 'is_used' => 0, 'is_deleted' => 0])
            ->find();
        if (!$get_one_cdkey) {
            return false;
        }
//        录入cdkey
        $savedata = [];
        $savedata['is_used'] = 1;
        $savedata['used_time'] = time();
        $res = Db::name("LotteryCdkey")
            ->where(['id' => $get_one_cdkey['id']])
            ->update($savedata);
        if ($res) {
            return $get_one_cdkey['cdkey'];
        } else {
            return false;
        }
    }

    /**
     * 获取抽奖列表
     */
    public static function get_pool($type = 0)
    {
        $res = Db::name('LotteryPool')
            ->where('type', $type)
            ->where('status', 1)
            ->where('is_deleted', 0)
            ->where('goods_num', '>', 0)
            ->order("is_free desc")
            ->limit(0, 6)
            ->select();
        return $res;
    }


    /**
     * 抽奖操作
     * @param $pool
     */
    public static function do_play($pool)
    {
        $rate = 100;
        $prizeList = [];
        $prize = [];
        $prizeZone = [];
        for ($i = 1; $i <= count($pool); $i++) {
            if (!$pool[$i - 1]['rate']) {
                continue;
            }
            $prize[$i] = $pool[$i - 1]['rate'];
            $rate -= $pool[$i - 1]['rate'];
            $prizeList[$i] = array($pool[$i - 1]['goods_name'], $pool[$i - 1]['id'], $i);
        }
//        默认的去掉
//        $prizeList = array_values($prizeList);
//        $prize = array_values($prize);
//        $keys = count($prizeList);
//        $prize[$keys] = $rate / 2;
//        $prizeList[$keys] = array('谢谢参与', '0', $keys + 1);
//        $prize[$keys + 1] = $rate / 2;
//        $prizeList[$keys + 1] = array('欢迎下次再来', '0', $keys + 2);

        //没有奖品退出
        if (!$prizeList) {
            return false;
        }

        $times = 10;
        $max = 0;
        foreach ($prize as $k => $v) {
            $max = $v * $times + $max;
            $row['v'] = $max;
            $row['k'] = $k;
            $prizeZone[] = $row;
        }

        $max--;                     //临界值
        $rand = mt_rand(0, $max);
        $zone = 1;
        foreach ($prizeZone as $k => $v) {
            if ($rand >= $v['v']) {
                if ($rand >= $prizeZone[$k + 1]['v']) {
                    continue;
                } else {
                    $zone = $prizeZone[$k + 1]['k'];
                    break;
                }
            }
            $zone = $v['k'];
            break;
        }
        return $prizeList[$zone];
    }

}